import Vue from 'vue'
import Router from 'vue-router'
import BlankView from '../framework/layouts/BlankView'
import {SSO} from "../sso/SSO";

try {
  const originalPush = Router.prototype.push
  Router.prototype.push = function push (location) {
    return originalPush.call(this, location).catch(err => err)
  }
} catch (e) {
}
Vue.use(Router)

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({
  showSpinner: false,
})

import routerConfig from './config'
import store from '../store'
import { INDEX_MAIN_PAGE_PATH } from '@/store/mutation-types'
import TokenStorageUtil from "../utils/TokenStorageUtil";

// window.__MICRO_APP_BASE_ROUTE__
// 设置基础路由，子应用可以通过window.__MICRO_APP_BASE_ROUTE__获取基座下发的baseroute，如果没有设置baseroute属性，则此值默认为空字符串
const router = new Router({
  mode: 'history',
  base: window.__MICRO_APP_BASE_ROUTE__ || process.env.BASE_URL,
  scrollBehavior: () => ({ y: 0 }),
  routes: routerConfig
})

const whiteList = [
  '/index/login',
  '/index/verificationCodeLogin',
  '/index/register',
  '/index/register-result',
  '/index/alteration',
  '/candidateInformation',
  '/examinationPaper',
  '/queryResults',
  '/flexform',
  "/flexform-success",
  '/integrityAndSatisfaction',
  '/questionnaireInvestigate',
  '/informationConfirmation',
  '/questionnaireInformation',
  '/classificationCapabilities',
  '/classificationInformation',
  '/inspectorInformationTable',
  '/consultationAppointmentTable',
  '/selectionRegistrationValidate',
  '/selectionRegistrationSelectType',
  '/selectionRegistrationInspectorInformationTable',
  '/selectionRegistrationOnlineEvaluation',
  '/onSiteInspectionCheckInSignedVersion',
  '/inspectorSystemPersonalInfoSignedVersion',
  '/onSiteInspectionCheckInFirsMeeting',
  '/onSiteInspectionCheckInInspectorCheckIn',
  '/onSiteInspectionCheckInToEvaluate',
  '/businessManagementSatisfactionSurvey',
  '/onSiteInspectionCheckInLastMeetingQD',
  '/aaRichTextrichText2'

]

router.beforeEach((to, from, next) => {
  //console.log('我真的得到了当前的路由吗？？？？？66666666',to, from, next)
  //console.log('没有跳转',store.getters.switchDepartments)
  NProgress.start()
  if(store.getters.switchDepartments){
    store.commit('SET_SWITCHDEPARTMENTS',false)
    store.dispatch('getNewMenuData')
    store.dispatch('GetPermissionList').then(res => {
      const menuData = res.result.menu
      const portalType = res.result.portalType
      const formOpenType = res.result.formOpenType
      store.dispatch("SetFormOpenType", formOpenType)
      store.dispatch("getCurrentModulemenuObj")

      if (menuData === null || menuData === '' || menuData === undefined) {
        return
      }
      let constRoutes = []
      constRoutes = generateIndexRouter(menuData, portalType)
      //console.log('我真的得到了当前的路由吗？？？？？77777777777',constRoutes)
      // 添加主界面路由
      store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
        // 根据roles权限生成可访问的路由表
        // 动态添加可访问路由表
        store.getters.addRouters.forEach(routeItem => {
          router.addRoute(routeItem) //添加路由，明天用到
        })
        //如果进到后台首页后刷新页面，再退出登录，换没有后台权限的账号首先进去得进到前台首页，所以就不能再用路由记录页面
        let redirect = ''
        if(from.path == '/index/login'){
          redirect = decodeURIComponent(store.state.user.onlyCurrentPath || INDEX_MAIN_PAGE_PATH)
        }else{
          redirect = decodeURIComponent(from.query.redirect || to.path)
        }
        
        //console.log('我真的得到了当前的路由吗？？？？？88888888888888',from.query.redirect,to.path)
        //console.log('我真的得到了当前的路由吗？？？？？88888888888888',redirect)
        if (to.path === redirect) {
          // hack方法 确保addRoutes已完成
          next({path:to.path})
        } 
      })
    }).catch((error) => {
      store.dispatch('Logout').then(() => {
        SSO.redirectUrl('/index/login', () => {
          next({path: '/index/login', query: {redirect: to.fullPath}})
        })
      })
    })
  }else{
    if (TokenStorageUtil.get()) {
      if (to.path === '/index/login') {
        SSO.redirectUrl('/index/login', () => {
          next({ path: '/' })
          NProgress.done()
        })
      } else {
        if (store.getters.permissionList.length === 0) {
          store.dispatch('getNewMenuData')
          store.dispatch('GetPermissionList').then(res => {
            const menuData = res.result.menu
            const portalType = res.result.portalType
            const formOpenType = res.result.formOpenType
            store.dispatch("SetFormOpenType", formOpenType)
            store.dispatch("getCurrentModulemenuObj")

            if (menuData === null || menuData === '' || menuData === undefined) {
              return
            }
            let constRoutes = []
            constRoutes = generateIndexRouter(menuData, portalType)
            //console.log('我真的得到了当前的路由吗？？？？？77777777777',constRoutes)
            // 添加主界面路由
            store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
              // 根据roles权限生成可访问的路由表
              // 动态添加可访问路由表
              store.getters.addRouters.forEach(routeItem => {
                router.addRoute(routeItem) //添加路由，明天用到
              })
              //如果进到后台首页后刷新页面，再退出登录，换没有后台权限的账号首先进去得进到前台首页，所以就不能再用路由记录页面
              let redirect = ''
              if(from.path == '/index/login'){
                redirect = decodeURIComponent(store.state.user.onlyCurrentPath || INDEX_MAIN_PAGE_PATH)
                store.commit('SET_CURRENTROUTERPATH', store.state.user.onlyCurrentPath?store.state.user.onlyCurrentPath:INDEX_MAIN_PAGE_PATH)
              }else{
                redirect = decodeURIComponent(from.query.redirect || to.path)
                store.commit('SET_CURRENTROUTERPATH', from.query.redirect?from.query.redirect:to.path)
              }
              
              //console.log('我真的得到了当前的路由吗？？？？？88888888888888',from.query.redirect,to.path)
              if (to.path === redirect) {
                // hack方法 确保addRoutes已完成
                next({ ...to, replace: true })
              } else {
                let firstChild = getFirstChild(to);
                //判断一级菜单配的是空组件跳转到子菜单
                if(firstChild && firstChild.path){
                  next({path:firstChild.path})
                }else{
                  // 跳转到目的路由
                  next({ path: redirect })
                }
              }
            })
          }).catch((error) => {
            store.dispatch('Logout').then(() => {
              SSO.redirectUrl('/index/login', () => {
                next({path: '/index/login', query: {redirect: to.fullPath}})
              })
            })
          })
        } else {
          let firstChild = getFirstChild(to);
          //判断一级菜单配的是空组件跳转到子菜单
          if(firstChild && firstChild.path){
            next({path:firstChild.path})
          }else{
            next()
          }
        }
      }
    } else {
      //console.log('我不是白名单吗？',whiteList.indexOf(to.path),to.path)
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单，直接进入
        SSO.redirectUrl(to.path, () => {
          next()
        })
      } else {
        SSO.redirectUrl('/index/login', () => {
          next({path: '/index/login', query: {redirect: to.fullPath}})
          NProgress.done()
        }, to.path)
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router

// 0标识前台菜单，1标识后台菜单
function generateIndexRouter (data, portalType) {
  let indexRouter = []
  //console.log('这个是路由的重新加载0',store.getters.back,store.state.user.info.backRoleFlg)
  //console.log(store.state.user.permissionList)
  let newMenuData = store.state.user.newMenuData
  let permissionList = store.state.user.permissionList
  let currentPath = ''
  //console.log('这是过滤后的路由',permissionList)
  //console.log('这是过滤后的路由1',newMenuData)
  if(newMenuData.length == 1 ){
    permissionList.forEach((item,index)=>{
      if(item.path == newMenuData[0].path){
        store.commit('SET_REWRITEGLOBALTABS', true)
        //console.log(item.children && item.children.length?item.children[0].path:item.path)
        store.commit('SET_ONLYCURRENTPATH', item.children && item.children.length?item.children[0].path:item.path)
        store.dispatch('getCurrentModulemenuObj',{...item,name:item.meta.title,childrenFirstPath:item.children[0].path})
        currentPath = item.children && item.children.length?item.children[0].path:item.path
        
      }
    })
  }else{
    store.commit('SET_ONLYCURRENTPATH', '')
    store.commit('SET_REWRITEGLOBALTABS', false)
  }
  //后台登录优先
  if (store.getters.back) {
    // 查找后台首页
    const consoleRouters = generateChildRouters(data, '1')
    let consoleIndex = consoleRouters.find(item => item.path === '/app/group')
    if (!consoleIndex) {
      consoleIndex = consoleRouters.find(item => item.path && item.name && !item.hidden)
    }
    store.commit('setConsoleIndex', consoleIndex)
    //console.log('这个是路由的重新加载1',store.getters.CONSOLE_INDEX_MAIN_PAGE_PATH)
    //后台
    indexRouter = [{
      path: '/',
      name: 'console-index',
      component: resolve => require(['@/framework/console/ConsoleTabLayout'], resolve),
      redirect: store.getters.CONSOLE_INDEX_MAIN_PAGE_PATH,
      children: [
        ...consoleRouters
      ]
    }]
  }
  if (typeof portalType != 'undefined' && portalType == '2') {
    //console.log('这个是路由的重新加载2',currentPath?currentPath:INDEX_MAIN_PAGE_PATH)
    indexRouter.push({
      path: '/',
      name: 'index',
      component: resolve => require(['@/framework/appPortal/AppPortalTabLayout'], resolve),
      redirect: currentPath?currentPath:INDEX_MAIN_PAGE_PATH,
      children: [
        ...generateChildRouters(data, '0')
      ]
    })
  } else {
    //console.log('这个是路由的重新加载3',currentPath?currentPath:INDEX_MAIN_PAGE_PATH)
    indexRouter.push({
      path: '/',
      name: 'index',
      component: resolve => require(['@/framework/defaultPortal/TabLayout'], resolve),
      redirect: currentPath?currentPath:INDEX_MAIN_PAGE_PATH,
      children: [
        ...generateChildRouters(data, '0')
      ]
    })
  }
  //console.log('这个是路由的重新加载4',indexRouter)
  return indexRouter
}

// 0标识前台菜单，1标识后台菜单
function generateChildRouters (data, back, parentPath) {
  let routers = []
  for (let item of data) {
    //如果不是需要的（前台或后台）菜单，跳过
    if (item.back !== back) {
      continue
    }

    let component = ''
    if (item.component.indexOf('layouts') >= 0) {
      component = 'framework/' + item.component
    } else {
      component = 'views/' + item.component
    }

    // URL支持{{ window.xxx }}占位符变量
    window._CONFIG['domianURL'] = bootConfig[process.env.NODE_ENV].VUE_APP_URL
    item.meta.url = (item.meta.url || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2))

    const props = {}
    let isEform = false;
    if (component.endsWith('eform/redirect/ViewLayoutRedirect')) {
      //页面
      props.viewCode = item.path.substring(item.path.lastIndexOf('/') + 1)
      props.isShowInTab = true
      isEform = true;
    } else if (component.endsWith('eform/redirect/ReportWidgetRedirectCard')) {
      //报表
      props.widgetCode = item.path.substring(item.path.lastIndexOf('/') + 1)
      isEform = true;
    } else if (component.endsWith('eform/redirect/FormRedirectAddTab')) {
      //表单
      props.formCode = item.path.substring(item.path.lastIndexOf('/') + 1)
      isEform = true;
    } else if (component.endsWith('bpm/redirect/RedirectAddTab')) {
      //流程
      const processDefId = item.path.substring(item.path.lastIndexOf('/') + 1)
      props.id = processDefId.replace(/@/g, ':')
      isEform = true;
    } else if (component.endsWith('layouts/MicroAppFrame')) {
      // 微前端应用
      const params = {
        microAppRoute: item.microAppRoute,
        microAppUrl: item.microAppUrl
      }
      props.params = params
    }

    let componentPath = resolve => require(['@/' + component + '.vue'], resolve)
    // let componentPath = async () => {
    //   let cpn = await import('@/' + component + '.vue')
    //   if (componentName) {
    //     cpn.default.name = componentName;
    //   }
    //   return cpn;
    // }

    let isIframe = false;
    if(component.endsWith('layouts/IframePageView')){
      isIframe = true;
    }

    // 组件参数
    // 电子表单一类的需要特殊处理，目前仅适用于列表页面的入参配置
    if (item.componentProps && item.componentProps !== '') {
      try {
        const componentProps = JSON.parse(item.componentProps)
        if (isEform) {
          const parameterValue = [];
          componentProps.forEach(componentProp => {
            if (componentProp.label) {
              parameterValue.push({
                colCode: componentProp.label,
                queryValue: componentProp.value
              })
            }
          })
          props['parameterValue'] = parameterValue
        } else {
          componentProps.forEach(componentProp => {
            if (componentProp.label) {
              props[componentProp.label] = componentProp.value
            }
          })
        }
      } catch (e) {
        //console.log(e)
      }
    }

    // 标识是页签的入口组件
    props.isSysRouteTabRoot = true

    let menu = {
      path: item.path,
      name: item.name,
      redirect: item.redirect,
      component: isIframe ? BlankView : componentPath,
      hidden: item.hidden,
      props: props,
      meta: {
        title: item.meta.title,
        icon: item.meta.icon,
        url: item.meta.url,
        permissionList: item.meta.permissionList,
        keepAlive: item.meta.keepAlive,
        internalOrExternal: item.meta.internalOrExternal,
        componentName: isIframe ? componentPath : undefined,
        parentPath: parentPath,
        isIframe: isIframe,
      }
    }
    if (item.alwaysShow) {
      menu.alwaysShow = true
      menu.redirect = menu.path
    }
    if (item.children && item.children.length > 0) {
      // menu.children = [...generateChildRouters(item.children, back)]
      routers = [...routers, ...generateChildRouters(item.children, back, [...(parentPath || []),item.path])]
    }
    // if (item.component.indexOf('layouts/RouteView') === -1) {
      routers.push(menu)
    // }
  }
  return routers
}

/**
 * 顶部+左侧菜单
 * 如果是一级菜单，并且配置的组件为空组件(layouts/RouteView)
 * 则获取一级菜单的第一个子菜单
 * @param to
 * @returns {*|*}
 */
function getFirstChild(to){
  let childMenu;
  const layout =  store.state.app.layout;
  if(layout=='topsidemenu'){
    const getFirstChild = (routes) => {
      const route = routes[0]
      if (!route.children || route.children.length === 0) {
        return route
      }
      return getFirstChild(route.children)
    }
    const  firstMenu = store.getters.firstMenu
    for (let menu of firstMenu) {
      if (to.path === menu.path) {
        //组件为空组件时
        if(menu.component == 'layouts/RouteView'){
          store.commit("setActivatedFirst", menu.path)
          const subMenu = store.getters.subMenu
          if (subMenu.length > 0) {
            childMenu = getFirstChild(subMenu)
            break
          }
        }
      }
    }
  }
  return childMenu;
}
